<?php

namespace App\Http\Controllers\Api;


use Illuminate\Http\Request;
use App\Http\Requests\Api\UserRequest;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
//use Auth;
use Illuminate\Support\Facades\DB;
use PhpParser\Node\Stmt\DeclareDeclare;

class UserController extends Controller
{
    //

    public function index(Request $request){
        $code = $request->code;
        return $code;
    }

//    //返回单一用户信息
//    public function show(User $user){
//        return $this->success($user);
//    }
//    //用户注册
//    public function store(UserRequest $request){
//        User::create($request->all());
//        return '用户注册成功。。。';
//    }
//    //用户登录
//    public function login(Request $request){
//
//        //$present_guard = Auth::getDefaultDriver();
//        //$token = Auth::claims(['guard'=>$present_guard])->attempt(['name' => $request->name, 'password' => $request->password]);
//        $token=Auth::guard('api')->attempt(['name'=>$request->name,'password'=>$request->password]);
//
//        if($token) {
//            return $this->setStatusCode(201)->success(['token' => 'bearer ' . $token]);
//        }
//        return $this->failed('账号或密码错误',400);
//    }


        //获取token
    public function setToken(Request $request)
    {
        $user_id = $request->id;


        $user = User::where('id',$user_id)->first();



        $token= auth('api')->login($user);

//        $token  = Auth::guard('api')->user();

        dd($token);
    }


    //返回当前登录用户信息
    public function info(){
        $user = Auth::guard('api')->user();

        $sign_data = DB::table('sign_users')
            ->where('u_id',$user->id)
            ->first();

        dd($sign_data);
        return $this->success($user);
    }


    //微信授权成功后返回用户信息，获取并存储
    public function getUserMsg(Request $request)
    {
        $user = Auth::guard('api')->user();
        $user_id = $user->id;
//        $data_user = $request->all();

        //查看数据库信息
        $data = User::where('id',$user_id)->first();
        $data_name = $data->name;
        $data_avatar = $data->avatar;
        $data_sex = $data->sex;

        //当数据库中不存在用户信息时才允许数据更新
        $name = $data_name == ''?$request->name:$data_name;
        $avatar = $data_avatar == ''?$request->avatar:$data_avatar;
        $sex = $data_sex == ''?$request->sex:$data_sex;


        if (empty($request->name)||empty($request->avatar)){
            return '上传信息缺失,上传失败';
        }else{

            $update = User::where('id',$user_id)->update([
                'name'=>$name,
                'avatar'=>$avatar,
                'sex'=>$sex,
            ]);

            return  $this->success($update);
        }
    }

}
